<?php
namespace app\common\config\logic;

use app\api\controller\audit\Config;
use app\common\BaseLogic;
use app\common\config\model\ConfigSource;

class DictionaryLogic extends BaseLogic
{
    


    public function getItem($id, $class, $fields="*")
    {
        $baseName = class_basename($class);
        $cacheName = "{$baseName}:{$id}";
        if ($fields == "*") {
            $data = $this->redis->hGetAll($cacheName);
        } else {
            $data = $this->redis->hMGet($cacheName, $fields);
        }


        if (empty($data['id'])) {
            $model = new $class;
            $row = $model->where('id', $id)->find();
            if (!empty($row)) {
                $data = $row->getData();
                $this->redis->hMSet($cacheName, $data);
                if ($fields != "*") $data = array_search_keys($data, $fields);
            } else {
                $data = [];
            }
        }

        return $data;
    }

    public function getFullPath($id) {
        $item = $this->getItem($id, ConfigSource::class);
        if (empty($item)) return [
            'id' => '',
            'title' => ''
        ];
        $path = explode('-', $item['path']);
        $path = array_filter($path);
        $items = [];
        foreach ($path as $row) {
            $source = $this->getItem($row, ConfigSource::class);
            array_push($items, $source['title']);
        }

        return [
            'id' => $id,
            'title' => implode('/', $items)
        ];
    }

    // 重置
    public function resetItemCache($id, $class)
    {
        $baseName = class_basename($class);
        $cacheName = "{$baseName}:{$id}";

        $this->redis->del($cacheName);
    }
}